﻿using System.Diagnostics;

namespace Equinoxe.EZNFC.Library
{
    public class Tools
    {


        [Conditional("TRACE")]
        static public void WriteTrace(string message, byte[] sendbuffer, int intsendbufferlength, byte[] receivedbuffer = null, int receivedbufferlength = 0)
        {
#if !SILVERLIGHT
            Trace.TraceInformation("************************************************");
            Trace.TraceInformation(message);
            if (sendbuffer != null)
                Trace.TraceInformation("Sendbuffer : " + BytesToString(sendbuffer, intsendbufferlength));
            if (receivedbuffer != null)
                Trace.TraceInformation("Receivedbuffer : " + BytesToString(receivedbuffer, receivedbufferlength));
#endif
        }

        static public string BytesToString(byte[] buffer, int bufferlength)
        {
            var tempstr = string.Empty;

            if (buffer == null)
                return tempstr;

            for (var i = 0; i < bufferlength; i++)
            {
                tempstr = tempstr + " " + string.Format("{0:X2}", buffer[i]);
            }
            return tempstr;
        }

        static public byte[] IntToByteArray(int value)
        {
             return new[] {
                (byte)value,
                (byte)(value >> 8),
                (byte)(value >> 16),
                (byte)(value >> 24)};
        }

        static public byte[] IntToComplementByteArray(int value)
        {
            var complement = uint.MaxValue - value;
            return new[] {
               (byte)complement,
                (byte)(complement >> 8),
                (byte)(complement >> 16),
                (byte)(complement >> 24)};
        }

        static public int ByteArrayToInt(byte[] array)
        {
            return array[0]
               + ((array[1] & 0xFF) << 8)
               + ((array[2] & 0xFF) << 16)
               + ((array[3] & 0xFF) << 24);
        }

        static public int ComplementByteArrayToInt(byte[] array)
        {
            return (255 - array[0])
               + (((255 - array[1]) & 0xFF) << 8)
               + (((255 - array[2]) & 0xFF) << 16)
               + (((255 - array[3]) & 0xFF) << 24);
        }

        static public byte[] ByteArrayToComplement(byte[] array)
        {
            return new[] {
                (byte)(255 - array[0]),
                (byte)(255 - array[1]),
                (byte)(255 - array[2]),
                (byte)(255 - array[3])};
        }
    }
}
